package com.shlh.saas.controller;

import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.service.IntelligentSearchService;
import com.shlh.saas.service.UserBalanceService;
import com.shlh.saas.service.WorkbenchStatsService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/intelligent-search")
public class IntelligentSearchController {

    private static final Logger log = LoggerFactory.getLogger(IntelligentSearchController.class);
    
    // 创建线程池用于并发搜索
    private final ExecutorService executorService = Executors.newFixedThreadPool(20);

    @Autowired
    private IntelligentSearchService searchService;
    
    @Autowired
    private WorkbenchStatsService workbenchStatsService;
    
    @Autowired
    private UserBalanceService userBalanceService;

    @GetMapping("")
    public Result<Map<String, Object>> searchData(
            @RequestParam String keyword,
            @RequestParam String type,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        // 添加详细调试日志
        log.info("收到智能搜索请求: 关键词={}, 类型={}, 页码={}, 页大小={}", keyword, type, page, size);
        
        // 获取当前用户ID
        Long userId = UserContext.getUserId();

        // 智能搜邮属于筛查操作，无论是第几页都需要扣除额度
            // 检查用户余额
            UserBalance userBalance = userBalanceService.getByUserId(userId);
            if (userBalance == null || userBalance.getReverseLookupRemaining() < size) {
                return Result.error("您的反查次数余额不足，请充值后再查看");
            }
            
            // 调用服务进行搜索
            Map<String, Object> result = searchService.searchData(keyword, type, page, size);
            log.info("搜索结果总数: {}", result.containsKey("total") ? result.get("total") : "未知");
            
            // 获取实际返回的数据条数
            int actualCount = 0;
        if (result.containsKey("results") && result.get("results") instanceof List) {
            actualCount = ((List<?>) result.get("results")).size();
            }
            
            // 扣除用户反查余额
            if (actualCount > 0) {
                userBalanceService.deductReverseLookup(userId, actualCount);
            }
            
            // 增加搜索次数统计
            workbenchStatsService.incrementIntelligentSearchCount(userId);
            
            return Result.success(result);
    }


    // 批量搜索接口
    @PostMapping("/batch")
    public ResponseEntity<?> batchSearchData(
            @RequestParam("file") MultipartFile file,
            @RequestParam(defaultValue = "1") Integer matchType) {

        // 添加详细调试日志
        log.info("收到批量智能搜索请求: 匹配类型：{}", matchType);

        // 获取当前用户ID
        Long userId = UserContext.getUserId();

        try {
            // 读取文件内容
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(Result.error("请选择要上传的Excel文件"));
            }

            // 检查文件类型
            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
                return ResponseEntity.badRequest().body(Result.error("文件格式不正确，只支持.xlsx和.xls格式"));
            }

            // 读取Excel文件 - 使用WorkbookFactory自动识别格式（支持.xls和.xlsx）
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            int totalRows = sheet.getPhysicalNumberOfRows();

            if (totalRows <= 1) { // 只有表头或为空
                workbook.close();
                return ResponseEntity.badRequest().body(Result.error("上传的Excel文件没有数据"));
            }

            // 获取表头
            Row headerRow = sheet.getRow(0);
            Map<String, Integer> headerMap = new HashMap<>();
            for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
                Cell cell = headerRow.getCell(i);
                if (cell != null) {
                    headerMap.put(cell.getStringCellValue(), i);
                }
            }

            // 验证必要的列：支持中英文两种格式
            boolean hasEnglishHeaders = headerMap.containsKey("CompanyName") && 
                                       headerMap.containsKey("FullName") && 
                                       headerMap.containsKey("Website");
            boolean hasChineseHeaders = headerMap.containsKey("公司名") && 
                                       headerMap.containsKey("姓名") && 
                                       headerMap.containsKey("网址");
            
            if (!hasEnglishHeaders && !hasChineseHeaders) {
                    workbook.close();
                return ResponseEntity.badRequest().body(Result.error("Excel文件缺少必要的列。请确保包含英文列（CompanyName、FullName、Website）或中文列（公司名、姓名、网址）"));
            }

            // 准备匹配结果文件
            Workbook resultWorkbook = new XSSFWorkbook();

            // 创建六个sheet分别对应不同的数据源，根据matchType动态生成表头
            Sheet facebookSheet = createSheetWithHeader(resultWorkbook, "Facebook数据", getFacebookHeaders(matchType));
            Sheet twitterSheet = createSheetWithHeader(resultWorkbook, "Twitter数据", getTwitterHeaders(matchType));
            Sheet linkedinSheet = createSheetWithHeader(resultWorkbook, "LinkedIn数据", getLinkedInHeaders(matchType));
            Sheet companySheet = createSheetWithHeader(resultWorkbook, "全球企业库", getCompanyHeaders(matchType));
            Sheet buyerSheet = createSheetWithHeader(resultWorkbook, "广交会采购商", getBuyerHeaders(matchType));
            Sheet exhibitorSheet = createSheetWithHeader(resultWorkbook, "广交会展商", getExhibitorHeaders(matchType));

            // 检查用户余额
            UserBalance userBalance = userBalanceService.getByUserId(userId);
            if (userBalance == null) {
                workbook.close();
                resultWorkbook.close();
                return ResponseEntity.badRequest().body(Result.error("用户余额信息不存在"));
            }

            // 统计各数据源找到的结果数量
            Map<String, Integer> resultCounts = new HashMap<>();
            resultCounts.put("facebook", 0);
            resultCounts.put("twitter", 0);
            resultCounts.put("linkedin", 0);
            resultCounts.put("company", 0);
            resultCounts.put("buyer", 0);
            resultCounts.put("exhibitor", 0);

            // 遍历数据行（从第1行开始，第0行是表头）
            for (int rowNum = 1; rowNum < totalRows; rowNum++) {
                Row dataRow = sheet.getRow(rowNum);
                if (dataRow == null) continue;

                // 获取搜索条件
                String companyName;
                String fullName;
                String website;
                if (headerMap.get("CompanyName") == null){
                    companyName = getCellStringValue(dataRow, headerMap.get("公司名"));
                } else {
                    companyName = getCellStringValue(dataRow, headerMap.get("CompanyName"));
                }
                if (headerMap.get("FullName") == null){
                    fullName = getCellStringValue(dataRow, headerMap.get("姓名"));
                }else {
                    fullName = getCellStringValue(dataRow, headerMap.get("FullName"));
                }
                if (headerMap.get("Website") == null){
                    website = getCellStringValue(dataRow, headerMap.get("网址"));
                } else {
                    website =  getCellStringValue(dataRow, headerMap.get("Website"));
                }

                // 如果所有条件都为空，跳过该行
                if ((companyName == null || companyName.trim().isEmpty()) &&
                        (fullName == null || fullName.trim().isEmpty()) &&
                        (website == null || website.trim().isEmpty())) {
                    continue;
                }

                // 并行搜索六个数据源
                List<CompletableFuture<Void>> searchTasks = new ArrayList<>();

                // 搜索Facebook数据
                searchTasks.add(CompletableFuture.runAsync(() -> {
                    try {
                        log.debug("开始搜索Facebook数据: companyName={}, fullName={}, website={}, matchType={}",
                                  companyName, fullName, website, matchType);
                        List<Map<String, Object>> facebookResults = searchFacebookData(companyName, fullName, website, matchType);
                        log.debug("Facebook搜索返回结果数: {}", facebookResults.size());

                        if (!facebookResults.isEmpty()) {
                            synchronized (facebookSheet) {
                                for (Map<String, Object> result : facebookResults) {
                                    Map<String, Object> mappedData = mapFacebookData(result, matchType);
                                    addDataToSheet(facebookSheet, mappedData, getFacebookHeaders(matchType));
                                    resultCounts.put("facebook", resultCounts.get("facebook") + 1);
                                }
                            }
                            log.info("Facebook数据写入完成，共{}条", facebookResults.size());
                        } else {
                            // 没有找到数据，不填充空行
                            log.debug("Facebook未找到匹配数据，跳过");
                        }
                    } catch (Exception e) {
                        log.error("搜索Facebook数据异常: companyName={}, fullName={}, website={}", companyName, fullName, website, e);
                        // 异常时也不填充空行
                    }
                }, executorService));

                // 搜索Twitter数据（类似Facebook的搜索逻辑）
                searchTasks.add(CompletableFuture.runAsync(() -> {
                    try {
                        List<Map<String, Object>> twitterResults = searchTwitterData(companyName, fullName, website, matchType);
                        if (!twitterResults.isEmpty()) {
                            synchronized (twitterSheet) {
                                for (Map<String, Object> result : twitterResults) {
                                    Map<String, Object> mappedData = mapTwitterData(result, matchType);
                                    addDataToSheet(twitterSheet, mappedData, getTwitterHeaders(matchType));
                                    resultCounts.put("twitter", resultCounts.get("twitter") + 1);
                                }
                            }
                        } else {
                            // 没有找到数据，不填充空行
                            log.debug("Twitter未找到匹配数据，跳过");
                        }
                    } catch (Exception e) {
                        log.error("搜索Twitter数据异常: companyName={}, fullName={}, website={}", companyName, fullName, website, e);
                        // 异常时也不填充空行
                    }
                }, executorService));

                // 搜索LinkedIn数据（类似逻辑）
                searchTasks.add(CompletableFuture.runAsync(() -> {
                    try {
                        List<Map<String, Object>> linkedinResults = searchLinkedInData(companyName, fullName, website, matchType);
                        if (!linkedinResults.isEmpty()) {
                            synchronized (linkedinSheet) {
                                for (Map<String, Object> result : linkedinResults) {
                                    Map<String, Object> mappedData = mapLinkedInData(result, matchType);
                                    addDataToSheet(linkedinSheet, mappedData, getLinkedInHeaders(matchType));
                                    resultCounts.put("linkedin", resultCounts.get("linkedin") + 1);
                                }
                            }
                        } else {
                            // 没有找到数据，不填充空行
                            log.debug("LinkedIn未找到匹配数据，跳过");
                        }
                    } catch (Exception e) {
                        log.error("搜索LinkedIn数据异常: companyName={}, fullName={}, website={}", companyName, fullName, website, e);
                        // 异常时也不填充空行
                    }
                }, executorService));

                // 搜索全球企业库数据（类似逻辑）
                searchTasks.add(CompletableFuture.runAsync(() -> {
                    try {
                        List<Map<String, Object>> companyResults = searchCompanyData(companyName, fullName, website, matchType);
                        if (!companyResults.isEmpty()) {
                            synchronized (companySheet) {
                                for (Map<String, Object> result : companyResults) {
                                    Map<String, Object> mappedData = mapCompanyData(result, matchType);
                                    addDataToSheet(companySheet, mappedData, getCompanyHeaders(matchType));
                                    resultCounts.put("company", resultCounts.get("company") + 1);
                                }
                            }
                        } else {
                            // 没有找到数据，不填充空行
                            log.debug("全球企业库未找到匹配数据，跳过");
                        }
                    } catch (Exception e) {
                        log.error("搜索全球企业库数据异常: companyName={}, fullName={}, website={}", companyName, fullName, website, e);
                        // 异常时也不填充空行
                    }
                }, executorService));

                // 搜索广交会采购商数据（类似逻辑）
                searchTasks.add(CompletableFuture.runAsync(() -> {
                    try {
                        List<Map<String, Object>> buyerResults = searchBuyerData(companyName, fullName, website, matchType);
                        if (!buyerResults.isEmpty()) {
                            synchronized (buyerSheet) {
                                for (Map<String, Object> result : buyerResults) {
                                    Map<String, Object> mappedData = mapBuyerData(result, matchType);
                                    addDataToSheet(buyerSheet, mappedData, getBuyerHeaders(matchType));
                                    resultCounts.put("buyer", resultCounts.get("buyer") + 1);
                                }
                            }
                        } else {
                            // 没有找到数据，不填充空行
                            log.debug("广交会采购商未找到匹配数据，跳过");
                        }
                    } catch (Exception e) {
                        log.error("搜索广交会采购商数据异常: companyName={}, fullName={}, website={}", companyName, fullName, website, e);
                        // 异常时也不填充空行
                    }
                }, executorService));

                // 搜索广交会展商数据（类似逻辑）
                searchTasks.add(CompletableFuture.runAsync(() -> {
                    try {
                        List<Map<String, Object>> exhibitorResults = searchExhibitorData(companyName, fullName, website, matchType);
                        if (!exhibitorResults.isEmpty()) {
                            synchronized (exhibitorSheet) {
                                for (Map<String, Object> result : exhibitorResults) {
                                    Map<String, Object> mappedData = mapExhibitorData(result, matchType);
                                    addDataToSheet(exhibitorSheet, mappedData, getExhibitorHeaders(matchType));
                                    resultCounts.put("exhibitor", resultCounts.get("exhibitor") + 1);
                                }
                            }
                        } else {
                            // 没有找到数据，不填充空行
                            log.debug("广交会展商未找到匹配数据，跳过");
                        }
                    } catch (Exception e) {
                        log.error("搜索广交会展商数据异常: companyName={}, fullName={}, website={}", companyName, fullName, website, e);
                        // 异常时也不填充空行
                    }
                }, executorService));

                // 等待所有搜索任务完成
                CompletableFuture.allOf(searchTasks.toArray(new CompletableFuture[0])).join();
            }

            workbook.close();

            // 计算总扣除额度（所有数据源找到的结果总数）
            int totalDeduction = resultCounts.values().stream().mapToInt(Integer::intValue).sum();

            // 检查余额是否足够
            if (userBalance.getReverseLookupRemaining() < totalDeduction) {
                resultWorkbook.close();
                return ResponseEntity.badRequest().body(Result.error("您的反查次数余额不足，需要扣除 " + totalDeduction + " 次，当前余额 " + userBalance.getReverseLookupRemaining() + " 次"));
            }

            // 移除没有数据的sheet（只有表头的sheet）
            removeEmptySheets(resultWorkbook);

            // 扣除用户反查余额
            if (totalDeduction > 0) {
                userBalanceService.deductReverseLookup(userId, totalDeduction);
            }

            // 增加搜索次数统计
            workbenchStatsService.incrementIntelligentSearchCount(userId);

            // 将结果Excel写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            resultWorkbook.write(outputStream);
            resultWorkbook.close();
            workbook.close();

            byte[] excelBytes = outputStream.toByteArray();
            outputStream.close();

            // 设置响应头
            String resultFileName = "批量搜索结果_" + System.currentTimeMillis() + ".xlsx";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", java.net.URLEncoder.encode(resultFileName, "UTF-8"));
            headers.setContentLength(excelBytes.length);

            log.info("批量搜索完成: 处理{}行数据，扣除{}次额度", totalRows - 1, totalDeduction);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(excelBytes);

        } catch (Exception e) {
            log.error("批量智能搜索异常", e);
            return ResponseEntity.status(500).body(Result.error("批量智能搜索异常: " + e.getMessage()));
        }
    }

    // 创建带表头的sheet[1](@ref)
    private Sheet createSheetWithHeader(Workbook workbook, String sheetName, String[] headers) {
        Sheet sheet = workbook.createSheet(sheetName);
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }
        return sheet;
    }

    // 移除没有数据的sheet（只有表头的sheet）
    private void removeEmptySheets(Workbook workbook) {
        // 从后向前遍历，避免删除后索引变化的问题
        for (int i = workbook.getNumberOfSheets() - 1; i >= 0; i--) {
            Sheet sheet = workbook.getSheetAt(i);
            // 如果sheet只有1行或0行（即只有表头或没有数据），则删除该sheet
            if (sheet.getLastRowNum() <= 0) {
                log.info("移除空sheet: {}", sheet.getSheetName());
                workbook.removeSheetAt(i);
            }
        }
    }

    // 添加数据到sheet[1](@ref)
    private void addDataToSheet(Sheet sheet, Map<String, Object> data, String[] headers) {
        int lastRowNum = sheet.getLastRowNum();
        Row row = sheet.createRow(lastRowNum + 1);

        for (int i = 0; i < headers.length; i++) {
            String header = headers[i];
            Object value = data.get(header);
            Cell cell = row.createCell(i);

            if (value != null) {
                if (value instanceof String) {
                    cell.setCellValue((String) value);
                } else if (value instanceof Number) {
                    cell.setCellValue(((Number) value).doubleValue());
                } else if (value instanceof Date) {
                    cell.setCellValue((Date) value);
                } else {
                    cell.setCellValue(value.toString());
                }
            } else {
                cell.setCellValue("");
            }
        }
    }

    // 获取单元格字符串值
    private String getCellStringValue(Row row, Integer columnIndex) {
        if (columnIndex == null || row == null) {
            return null;
        }
        Cell cell = row.getCell(columnIndex);
        if (cell == null) {
            return null;
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                return String.valueOf((long) cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return null;
        }
    }

    // 各数据源的表头定义
    // matchType: 1-带手机号, 2-带邮箱
    private String[] getFacebookHeaders(Integer matchType) {
        if (matchType != null && matchType == 1) {
            // 带手机号：不显示邮箱列
            return new String[]{ "FacebookID", "姓名", "电话", "性别", "工作地点", "所在城市",  "出生地点", "个人状态", "出生日期", "加入时间"};
        } else {
            // 带邮箱（默认）：不显示电话列
            return new String[]{ "FacebookID", "姓名", "邮箱", "性别", "工作地点", "所在城市",  "出生地点", "个人状态", "出生日期", "加入时间"};
        }
    }

    private String[] getTwitterHeaders(Integer matchType) {
        if (matchType != null && matchType == 1) {
            // 带手机号：不显示邮箱列
            return new String[]{ "姓名", "屏幕名", "粉丝数", "创建时间"};
        } else {
            // 带邮箱（默认）：显示邮箱列
        return new String[]{ "姓名", "邮箱", "屏幕名", "粉丝数", "创建时间"};
        }
    }


    private String[] getLinkedInHeaders(Integer matchType) {
        if (matchType != null && matchType == 1) {
            // 带手机号：不显示邮箱列
            return new String[]{"公司名", "人名", "网址",  "职位", "行业", "电话", "手机号", "位置",  "地点", "国家", "公司规模", "twitter用户", "twitter链接", "LinkedIn链接", "GitHub链接", "Facebook链接" };
        } else {
            // 带邮箱（默认）：不显示电话、手机号列
            return new String[]{"公司名", "人名", "网址",  "职位", "行业", "邮箱", "位置",  "地点", "国家", "公司规模", "twitter用户", "twitter链接", "LinkedIn链接", "GitHub链接", "Facebook链接" };
        }
    }


    private String[] getCompanyHeaders(Integer matchType) {
        if (matchType != null && matchType == 1) {
            // 带手机号：不显示邮箱列
            return new String[]{"公司名", "姓名", "职位", "省份", "行业", "子行业", "员工规模", "收入规模", "电话", "手机号", "网址", "地址", "邮编"};
        } else {
            // 带邮箱（默认）：不显示电话、手机号列
            return new String[]{"公司名", "姓名", "职位", "省份", "行业", "子行业", "员工规模", "收入规模", "网址", "邮箱", "地址", "邮编"};
        }
    }

    private String[] getBuyerHeaders(Integer matchType) {
        if (matchType != null && matchType == 1) {
            // 带手机号：不显示邮箱列
            return new String[]{"公司名", "联系人", "国家/地区", "采购类型", "网址", "电话", "传真", "地址", "邮编", "广交会届数"};
        } else {
            // 带邮箱（默认）：不显示电话列
            return new String[]{"公司名", "联系人", "国家/地区", "采购类型", "网址", "邮箱", "传真", "地址", "邮编", "广交会届数"};
        }
    }

    private String[] getExhibitorHeaders(Integer matchType) {
        if (matchType != null && matchType == 1) {
            // 带手机号：不显示邮箱列
            return new String[]{"公司名", "公司类型", "公司简介",  "联系人", "手机号", "固定电话", "网址", "地址", "传真", "邮编", "行业", "省份", "展位号", "主要产品", "公司规模", "成立年份", "注册资金", "历史参展", "届次"};
        } else {
            // 带邮箱（默认）：不显示手机号、固定电话列
            return new String[]{"公司名", "公司类型", "公司简介",  "联系人", "网址", "地址",  "邮箱" , "传真", "邮编", "行业", "省份", "展位号", "主要产品", "公司规模", "成立年份", "注册资金", "历史参展", "届次"};
        }
    }

    // 搜索各数据源的方法（需要您在IntelligentSearchService中实现）
    private List<Map<String, Object>> searchFacebookData(String companyName, String fullName, String website, Integer matchType) {
        // 调用IntelligentSearchService中的方法搜索Facebook数据,facebook库没有website字段
        if(website != null){
            return new ArrayList<>();
        }
        return searchService.searchFacebookData(companyName, fullName, matchType);
    }

    private List<Map<String, Object>> searchTwitterData(String companyName, String fullName, String website, Integer matchType) {
        // 调用IntelligentSearchService中的方法搜索Twitter数据,twitter库没有website字段
        if(website != null){
            return new ArrayList<>();
        }
        return searchService.searchTwitterData(companyName, fullName, matchType);
    }

    private List<Map<String, Object>> searchLinkedInData(String companyName, String fullName, String website, Integer matchType) {
        // 调用IntelligentSearchService中的方法搜索LinkedIn数据
        return searchService.searchLinkedInData(companyName, fullName, website, matchType);
    }

    private List<Map<String, Object>> searchCompanyData(String companyName, String fullName, String website, Integer matchType) {
        // 调用IntelligentSearchService中的方法搜索全球企业库数据
        return searchService.searchCompanyData(companyName, fullName, website, matchType);
    }

    private List<Map<String, Object>> searchBuyerData(String companyName, String fullName, String website, Integer matchType) {
        // 调用IntelligentSearchService中的方法搜索广交会采购商数据
        return searchService.searchBuyerData(companyName, fullName, website, matchType);
    }

    private List<Map<String, Object>> searchExhibitorData(String companyName, String fullName, String website, Integer matchType) {
        // 调用IntelligentSearchService中的方法搜索广交会展商数据
        return searchService.searchExhibitorData(companyName, fullName, website, matchType);
    }
    
    // 创建空行数据（用于未找到结果或异常的情况）
    private Map<String, Object> createEmptyRowData(String companyName, String fullName, String website, String status) {
        Map<String, Object> data = new HashMap<>();
        // 为所有可能的列添加空值或状态标记
        data.put("状态", status);
        data.put("原始公司名", companyName);
        data.put("原始姓名", fullName);
        data.put("原始网址", website);
        return data;
    }
    
    // 将Facebook数据映射到Excel表头
    private Map<String, Object> mapFacebookData(Map<String, Object> source, Integer matchType) {
        Map<String, Object> mapped = new HashMap<>();
        // 基础字段
        mapped.put("FacebookID", source.get("facebook_id"));
        mapped.put("姓名", source.get("name"));
        
        // 根据matchType决定包含的字段
        if (matchType != null && matchType == 1) {
            // 带手机号：包含电话
        mapped.put("电话", source.get("phone"));
        } else {
            // 带邮箱：包含邮箱
        mapped.put("邮箱", source.get("email"));
        }
        
        // 其他公共字段
        mapped.put("性别", source.get("gender"));
        mapped.put("工作地点", source.get("workplace"));
        mapped.put("所在城市", source.get("current_location")); // 当前所在城市
        mapped.put("出生地点", source.get("hometown")); // 家乡/出生地
        mapped.put("个人状态", source.get("relationship_status"));
        mapped.put("出生日期", source.get("date"));
        mapped.put("加入时间", source.get("join_date"));
        return mapped;
    }
    
    // 将Twitter数据映射到Excel表头
    private Map<String, Object> mapTwitterData(Map<String, Object> source, Integer matchType) {
        Map<String, Object> mapped = new HashMap<>();
        // 基础字段
        mapped.put("姓名", source.get("name"));
        
        // 根据matchType决定包含的字段
        if (matchType != null && matchType == 2) {
            // 带邮箱：包含邮箱
        mapped.put("邮箱", source.get("email"));
        }
        // matchType == 1时不包含邮箱
        
        // 其他公共字段
        mapped.put("屏幕名", source.get("screen_name"));
        mapped.put("粉丝数", source.get("followers"));
        mapped.put("创建时间", source.get("created_at"));
        return mapped;
    }
    
    // 将LinkedIn数据映射到Excel表头
    private Map<String, Object> mapLinkedInData(Map<String, Object> source, Integer matchType) {
        Map<String, Object> mapped = new HashMap<>();
        // 基础字段
        mapped.put("公司名", source.get("company_name"));
        mapped.put("人名", source.get("full_name"));
        mapped.put("网址", source.get("company_website"));
        mapped.put("职位", source.get("job_title"));
        mapped.put("行业", source.get("industry"));
        
        // 根据matchType决定包含的字段
        if (matchType != null && matchType == 1) {
            // 带手机号：包含电话和手机号
        mapped.put("电话", source.get("phone_numbers"));
        mapped.put("手机号", source.get("phone_numbers"));
        } else {
            // 带邮箱：包含邮箱
            mapped.put("邮箱", source.get("emails"));
        }
        
        // 其他公共字段
        mapped.put("位置", source.get("location"));
        mapped.put("地点", source.get("location"));
        mapped.put("国家", source.get("country"));
        mapped.put("公司规模", source.get("company_size"));
        mapped.put("twitter用户", source.get("twitter_username"));
        mapped.put("twitter链接", source.get("twitter_url"));
        mapped.put("LinkedIn链接", source.get("linkedin_url"));
        mapped.put("GitHub链接", source.get("github_url"));
        mapped.put("Facebook链接", source.get("facebook_url"));
        return mapped;
    }
    
    // 将全球企业库数据映射到Excel表头
    private Map<String, Object> mapCompanyData(Map<String, Object> source, Integer matchType) {
        Map<String, Object> mapped = new HashMap<>();
        
        // 组合姓名
        String fullName = "";
        Object firstName = source.get("first_name");
        Object middleName = source.get("middle_name");
        Object lastName = source.get("last_name");
        
        if (firstName != null && !firstName.toString().isEmpty()) {
            fullName += firstName;
        }
        if (middleName != null && !middleName.toString().isEmpty()) {
            if (!fullName.isEmpty()) fullName += " ";
            fullName += middleName;
        }
        if (lastName != null && !lastName.toString().isEmpty()) {
            if (!fullName.isEmpty()) fullName += " ";
            fullName += lastName;
        }
        
        // 基础字段
        mapped.put("公司名", source.get("company_name"));
        mapped.put("姓名", fullName);
        mapped.put("职位", source.get("title"));
        mapped.put("省份", source.get("state"));
        mapped.put("行业", source.get("industry"));
        mapped.put("子行业", source.get("sub_industry"));
        mapped.put("员工规模", source.get("employee_size"));
        mapped.put("收入规模", source.get("revenue_size"));
        
        // 根据matchType决定包含的字段
        if (matchType != null && matchType == 1) {
            // 带手机号：包含电话和手机号
        mapped.put("电话", source.get("phone"));
        mapped.put("手机号", source.get("mobile"));
        } else {
            // 带邮箱：包含邮箱
            mapped.put("邮箱", source.get("email"));
        }
        
        // 其他公共字段
        mapped.put("网址", source.get("web_address"));
        mapped.put("地址", source.get("address"));
        mapped.put("邮编", source.get("zip_code"));
        return mapped;
    }
    
    // 将广交会采购商数据映射到Excel表头
    private Map<String, Object> mapBuyerData(Map<String, Object> source, Integer matchType) {
        Map<String, Object> mapped = new HashMap<>();
        // 基础字段
        mapped.put("公司名", source.get("company_name"));
        mapped.put("联系人", source.get("contact_person"));
        mapped.put("国家/地区", source.get("country"));
        mapped.put("采购类型", source.get("purchase_type"));
        mapped.put("网址", source.get("website"));
        
        // 根据matchType决定包含的字段
        if (matchType != null && matchType == 1) {
            // 带手机号：包含电话
            mapped.put("电话", source.get("phone"));
        } else {
            // 带邮箱：包含邮箱
        mapped.put("邮箱", source.get("email"));
        }
        
        // 其他公共字段
        mapped.put("传真", source.get("fax"));
        mapped.put("地址", source.get("address"));
        mapped.put("邮编", source.get("zip_code"));
        mapped.put("广交会届数", source.get("session_info"));
        return mapped;
    }
    
    // 将广交会展商数据映射到Excel表头
    private Map<String, Object> mapExhibitorData(Map<String, Object> source, Integer matchType) {
        Map<String, Object> mapped = new HashMap<>();
        // 基础字段
        mapped.put("公司名", source.get("company_name"));
        mapped.put("公司类型", source.get("company_type"));
        mapped.put("公司简介", source.get("company_description"));
        mapped.put("联系人", source.get("contact_person"));
        
        // 根据matchType决定包含的字段
        if (matchType != null && matchType == 1) {
            // 带手机号：包含手机号和固定电话
        mapped.put("手机号", source.get("mobile"));
        mapped.put("固定电话", source.get("phone"));
        } else {
            // 带邮箱：包含邮箱
            mapped.put("邮箱", source.get("email"));
        }
        
        // 其他公共字段
        mapped.put("网址", source.get("website"));
        mapped.put("地址", source.get("address"));
        mapped.put("传真", source.get("fax"));
        mapped.put("邮编", source.get("zip_code"));
        mapped.put("行业", source.get("category"));
        mapped.put("省份", source.get("province"));
//        mapped.put("国家", source.get("country"));
//        mapped.put("城市", source.get("city"));
        mapped.put("展位号", source.get("booth_number"));
        mapped.put("主要产品", source.get("main_products"));
        mapped.put("公司规模", source.get("company_size"));
        mapped.put("成立年份", source.get("established_year"));
        mapped.put("注册资金", source.get("registered_capital"));
        mapped.put("历史参展", source.get("exhibition_history"));
        mapped.put("届次", source.get("session_info"));
        return mapped;
    }

    /**
     * 下载批量搜索模板
     * @param lang 语言（zh/en）
     */
    @GetMapping("/batch/template")
    public ResponseEntity<byte[]> downloadTemplate(@RequestParam(defaultValue = "zh") String lang) {
        try {
            String templatePath;
            String fileName;
            
            if ("en".equals(lang)) {
                templatePath = "static/templates/intelligent/Intelligent Postal Search.xls";
                fileName = "Intelligent_Postal_Search.xls";
            } else {
                templatePath = "static/templates/intelligent/智能搜邮.xls";
                fileName = "智能搜邮.xls";
            }
            
            Resource resource = new ClassPathResource(templatePath);
            InputStream inputStream = resource.getInputStream();
            byte[] bytes = inputStream.readAllBytes();
            inputStream.close();
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", java.net.URLEncoder.encode(fileName, "UTF-8"));
            headers.setContentLength(bytes.length);
            
            return ResponseEntity.ok().headers(headers).body(bytes);
        } catch (Exception e) {
            log.error("下载模板失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }
} 